package com.app.newiptv.presenter;

import android.app.Activity;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;
import com.app.newiptv.activity.DownLoadApp;
import com.app.newiptv.activity.PlayerActivity;
import com.app.newiptv.activity.VodActivity;
import com.app.newiptv.base.MyApplication;
import com.app.newiptv.bean.AppInfo;
import com.app.newiptv.bean.Content;
import com.app.newiptv.bean.HomePageBean;
import com.app.newiptv.bean.LiveListBean;
import com.app.newiptv.callback.IRequestCallback;
import com.app.newiptv.promote.UpgradeUtil;
import com.app.newiptv.promote.UserRecodeRunnable;
import com.app.newiptv.service.AHservice;
import com.app.newiptv.utils.APPLog;
import com.app.newiptv.utils.Paths;
import java.io.File;
import java.util.ArrayList;
import java.util.List;


/**
 * Created by wendal on 2017/9/23.
 */

public class HomePagePresenter implements UpgradeUtil.DownloadListener{
    private boolean isDisplayed;
    private Callback callback;
    private HomePageBean homePageBeen;
    private List<HomePageBean.Menus> menusList;
    private List<HomePageBean.Hots> hotsList;
    private List<Content> vodContent;
    private AHservice service;
    private Activity mActivity;
    private String appFile;
    private RelativeLayout programLayout;
    private TextView textView;
    private long progress;
    private long max;
    private SharedPreferences sharedPreferences;
    private boolean isPlayLive;
    private Runnable loadingDisplayText = new Runnable() {
        @Override
        public void run() {
            if(progress>=max-2048){
                programLayout.setVisibility(View.GONE);
            }else{
                programLayout.setVisibility(View.VISIBLE);
                textView.setText("正在下载中....." + " " + progress + "/" + max);
            }
        }
    };
    private Handler handler = new Handler(){
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            Toast.makeText(mActivity, "下载失败", Toast.LENGTH_SHORT).show();
        }
    };
    public HomePagePresenter(Activity mActivity) {
        this.mActivity = mActivity;
        appFile = Environment.getExternalStorageDirectory().getPath()
                + "/AHIPTVLauncher/spfile/";
    }
    public void setLayout(RelativeLayout programLayout){
        this.programLayout = programLayout;
    }
    public void setTextView(TextView textView){
        this.textView = textView;
    }
    public void setSharedPreferences(SharedPreferences sharedPreferences){
        this.sharedPreferences = sharedPreferences;
    }
    public void setIsPlayLive(boolean isPlayLive){
        this.isPlayLive = isPlayLive;
    }
    @Override
    public void onLoading(int progress, int contentLen) {
        this.progress = progress;
        this.max = contentLen;
        textView.post(loadingDisplayText);
    }

    @Override
    public void onLoaded(File apk) {
        UpgradeUtil.install(mActivity,apk);
    }

    @Override
    public void onFailed() {
        handler.sendEmptyMessage(0);
    }

    public interface Callback {
        void onError(int code, String msg);

        void onHomePageCompleted(HomePagePresenter presenter, int count1, HomePageBean dto);

        void onNoticCompleted(HomePagePresenter presenter);
    }

    public interface MiddleViewHolder {
        void setImage(String imageUrl);
    }

    public interface LeftViewHolder {
        void setImage(String imageUrl);
    }

    public interface BottomViewHolder {
        void setImage(String imageUrl);

        void setText(String text);
    }

    public void setDisplayed(boolean isDisplayed) {
        this.isDisplayed = isDisplayed;
    }

    public void loadData(Callback callback) {
        if (callback != null) {
            this.callback = callback;
        }
        service = new AHservice();
        service.loadHomePagedData(Paths.HOSTPATH + Paths.HOME_INDEX, new ItemLoadCallback());
    }

    public void loadHomeNotic() {
        if (service == null) {
            service = new AHservice();
        }
        service.loadNoticData("", new MarQueeCallBack());
    }

    public void loadLiveList() {
        service = new AHservice();
        service.loadLiveListCallback(Paths.HOSTPATH + Paths.PROGRAM_LIVE, new LiveListCallback());
    }

    public void onBindMiddleData(MiddleViewHolder viewHolder, int position) {
        if (hotsList != null && position < hotsList.size()) {
            viewHolder.setImage(Paths.HOSTPATH + hotsList.get(position).getImage());
        }
    }

    public void onBindBottomData(BottomViewHolder viewHolder, int position) {
        if (menusList != null) {
            if (position == menusList.size()) {
                viewHolder.setImage("set");
                viewHolder.setText("设置");
            } else {
                viewHolder.setImage(menusList.get(position).getImage());
                viewHolder.setText(menusList.get(position).getName());
            }
        }
    }

    public Bundle getParams(int position) {
        Bundle bundle = new Bundle();
        HomePageBean.Hots hots = hotsList.get(position);
        bundle.putInt("id", hots.getId());
        return bundle;
    }

    public void getBottomParams(int position) {
        if (position == menusList.size()) {
            PackageManager packageManager = mActivity.getPackageManager();
            Intent intent = new Intent();
            intent = packageManager.getLaunchIntentForPackage("com.android.settings");
            mActivity.startActivity(intent);
            return;
        }
        if (menusList != null && position < menusList.size()) {
            final HomePageBean.Menus menus = menusList.get(position);
            String type = menus.getType();
            APPLog.printInfo("menutype==>:" + type);
            if (menus != null) {
                switch (menus.getType()) {
                    case "link":

                        break;
                    case "app":
                        List<AppInfo> apps = loadAppInfos();
                        boolean isHas = false;
                        String spPackageName = menus.getApp().getName();
                        APPLog.printInfo("spPackageName:" + spPackageName);
                        Toast.makeText(mActivity, "spPackageName:"+spPackageName, Toast.LENGTH_LONG).show();
                        for (int i = 0; i < apps.size(); i++) {
                            String appPackageName = apps.get(i).getPackagename();
                            if (appPackageName.equals(spPackageName)) {
                                PackageManager packageManager = mActivity.getPackageManager();
                                Intent intent = new Intent();
                                intent = packageManager.getLaunchIntentForPackage(appPackageName);
                                mActivity.startActivity(intent);
                                isHas = true;
//					Toast.makeText(getActivity(), "appPackageName:"+appPackageName+"applyName:"+applyName, Toast.LENGTH_SHORT).show();
                            }
                        }
                        if(!isHas){
                            final String downLoad = Paths.HOSTPATH + menus.getApp().getDownload();
                            APPLog.printInfo("下载地址："+downLoad);
                                new Thread(new Runnable() {
                                    @Override
                                    public void run() {
                                        try {
                                            DownLoadApp.upgrade(downLoad,appFile,HomePagePresenter.this);
                                        } catch (Exception e) {
                                            e.printStackTrace();
                                        }
                                    }
                                }).start();
                            Toast.makeText(mActivity, "正在下载APP，请稍等......", Toast.LENGTH_SHORT).show();
                        }
                        break;
                    case "video":
                        Bundle bundle = new Bundle();
                        bundle.putString("menuUrl", menus.getUrl());
                        Intent intent = new Intent();
                        intent.putExtra("bundle", bundle);
                        intent.setClass(mActivity, VodActivity.class);
                        mActivity.startActivity(intent);
                        break;
                    case "live":
                        //mActivity.startActivity(new Intent(mActivity, AllChannelsActivity.class));
                        int id = sharedPreferences.getInt("id",0);
                        if(id==0) {
                            id = MyApplication.liveListBeen.get(0).getId();
                        }
                        Intent intent1 = new Intent();
                        intent1.setClass(mActivity, PlayerActivity.class);
                        intent1.putExtra("type",1004);
                        intent1.putExtra("index",id);
                        mActivity.startActivity(intent1);
                        break;
                }
            }
        }
    }
    //public void shipPlayer(){
    //    int id = sharedPreferences.getInt("id",0);
    //    if(id==0&&MyApplication.liveListBeen.size()>0) {
    //        id = MyApplication.liveListBeen.get(0).getId();
    //    }
    //    Intent intent1 = new Intent();
    //    intent1.setClass(mActivity, PlayerActivity.class);
    //    intent1.putExtra("type",1004);
    //    intent1.putExtra("index",id);
    //    mActivity.startActivity(intent1);
    //}
    public boolean getVodType(int position) {
        HomePageBean.Hots hots = hotsList.get(position);
        if (hots.getTotal_episode() == 1) {
            return true;
        }
        return false;
    }

    public boolean getTelType(int position) {
        HomePageBean.Hots hots = hotsList.get(position);
        if (hots.getTotal_episode() > 1) {
            return true;
        }
        return false;
    }

    class ItemLoadCallback implements IRequestCallback {
        @Override
        public void onFailed(String arg0, String arg1) {
        }

        @Override
        public void onLoadComplete(String contentID, int pageNumber, int count, Object dto) {
            if (callback == null || !isDisplayed) {
                APPLog.printInfo("onLoadComplete:callback :");
                return;
            }
            if (dto != null && dto instanceof HomePageBean) {
                homePageBeen = (HomePageBean) dto;
                menusList = homePageBeen.getMenus();
                hotsList = homePageBeen.getHots();
                callback.onHomePageCompleted(HomePagePresenter.this, 20, homePageBeen);

            }
        }

        @Override
        public void onLoading(String arg0) {
        }
    }

    class MarQueeCallBack implements IRequestCallback {

        @Override
        public void onLoadComplete(String contentID, int pageNumber, int count, Object dto) {
            callback.onNoticCompleted(HomePagePresenter.this);
        }

        @Override
        public void onLoading(String contentID) {

        }

        @Override
        public void onFailed(String code, String msg) {

        }
    }

    class LiveListCallback implements IRequestCallback {

        @Override
        public void onLoadComplete(String contentID, int pageNumber, int count, Object dto) {
            if (dto != null && dto instanceof List) {
                MyApplication.liveListBeen = (List<LiveListBean>) dto;
                if(isPlayLive){
                    int id = sharedPreferences.getInt("id",0);
                        if(id==0&&MyApplication.liveListBeen.size()>0) {
                            id = MyApplication.liveListBeen.get(0).getId();
                        }

                        APPLog.printDebug("PlayerActivity  onLoadComplete  onCreate");

                        Intent intent1 = new Intent();
                        intent1.setClass(mActivity, PlayerActivity.class);
                        intent1.putExtra("type",1004);
                        intent1.putExtra("index",id);
                        mActivity.startActivity(intent1);
                }
            }
        }

        @Override
        public void onLoading(String contentID) {

        }

        @Override
        public void onFailed(String code, String msg) {

        }
    }
    public  List<AppInfo> loadAppInfos(){
        PackageManager pm = mActivity.getPackageManager();
        //创建要返回的集合对象
        List<AppInfo> appInfos = new ArrayList<AppInfo>();
        //获取手机中所有安装的应用集合
        List<ApplicationInfo> applicationInfos = pm.getInstalledApplications(0);

        APPLog.printInfo("applicationInfos.size()------------------------"+applicationInfos.size());
        //遍历所有的应用集合
        for(ApplicationInfo info : applicationInfos){
            if ((info.flags & ApplicationInfo.FLAG_SYSTEM) == 0) {	// 非系统应用
                AppInfo appInfo = new AppInfo();
                //获取应用程序的图标
                Drawable app_icon = info.loadIcon(pm);
                APPLog.printInfo("app_icon------------------------"+app_icon);
                appInfo.setApp_icon(app_icon);

                //获取应用的名称
                String app_name = info.loadLabel(pm).toString();
                APPLog.printInfo("aapp_name------------------------"+app_name);
                appInfo.setApp_name(app_name);

                //获取应用的包名
                String packageName = info.packageName;
                APPLog.printInfo("packageName------------------------"+packageName);
                appInfo.setPackagename(packageName);
                try {
                    //获取应用的版本号
                    PackageInfo packageInfo = pm.getPackageInfo(packageName, 0);
                    String app_version = packageInfo.versionName;
                    APPLog.printInfo("app_version------------------------"+app_version);
                    appInfo.setApp_version(app_version);
                } catch (PackageManager.NameNotFoundException e) {
                    e.printStackTrace();
                }
                //判断应用程序是否是用户程序
//			boolean isUserApp = filterApp(info);
//			appInfo.setUserApp(isUserApp);
                appInfos.add(appInfo);
            }
        }
        return appInfos;
    }
}














